package demo.app.nexd.com.demo;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.race604.flyrefresh.FlyRefreshLayout;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class ShoppingListActivity extends Activity implements FlyRefreshLayout.OnPullRefreshListener {

    private FlyRefreshLayout mFlylayout;
    private RecyclerView mListView;

    private ItemAdapter mAdapter;

    private ArrayList<ItemData> mDataSet = new ArrayList<>();
    private Handler mHandler = new Handler();
    private LinearLayoutManager mLayoutManager;
    private Timer time;
    private boolean isFinish = false;
    private List<ItemData> preItems = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initDataSet();
        setContentView(R.layout.shopping);

//        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);
//        getSupportActionBar().setDisplayShowTitleEnabled(false);

        mFlylayout = (FlyRefreshLayout) findViewById(R.id.fly_layout);

        mFlylayout.setOnPullRefreshListener(this);

        mListView = (RecyclerView) findViewById(R.id.list);

        mLayoutManager = new LinearLayoutManager(this);
        mListView.setLayoutManager(mLayoutManager);
        mAdapter = new ItemAdapter(this);
        time = new Timer();
        mListView.setAdapter(mAdapter);

        mListView.setItemAnimator(new SampleItemAnimator());

        View actionButton = mFlylayout.getHeaderActionButton();
        if (actionButton != null) {
            actionButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    mFlylayout.startRefresh();
                }
            });
        }
    }

    private void initDataSet() {
        preItems.add(new ItemData(R.drawable.youyiku, "优衣库", new Date(), "yykqj.png"));
        preItems.add(new ItemData(R.drawable.hla, "海澜之家", new Date(), "hlaqj2.png"));
        preItems.add(new ItemData(R.drawable.hm, "H&M", new Date(), "hmqj.png"));
//        mDataSet.add(new ItemData(/*Color.parseColor("#76A9FC"),*/ R.mipmap.ic_assessment_white_24dp, "Meeting Minutes", new Date(2014 - 1900, 2, 9), "http://www.baidu.com"));
//        mDataSet.add(new ItemData(/*Color.GRAY, */R.mipmap.ic_folder_white_24dp, "Favorites Photos", new Date(2014 - 1900, 1, 3), "http://www.jd.com"));
//        mDataSet.add(new ItemData(/*Color.GRAY, */R.mipmap.ic_folder_white_24dp, "Photos", new Date(2014 - 1900, 0, 9), "http://www.taobao.com"));
    }

    int index = 0;

    private void addItemData() {
//        ItemData itemData = new ItemData(/*Color.parseColor("#FFC970"),*/ R.mipmap.ic_smartphone_white_24dp, "Magic Cube Show", new Date(), "http://www.github.com");
//        mDataSet.add(0, itemData);
        mDataSet.add(0, preItems.get(index));
        index++;
        mAdapter.notifyItemInserted(0);
        mLayoutManager.scrollToPosition(0);
    }


    @Override
    protected void onResume() {
        super.onResume();



        if (!isFinish) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setTitle("通知").setMessage("检索到您身边的优惠商家，是否点击查看?").setPositiveButton("查看", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();

                    time.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            for (int i = 0; i < preItems.size(); i++) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mFlylayout.startRefresh();
                                    }
                                });
                                try {
                                    Thread.sleep(3000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            isFinish = true;

                        }
                    }, 500);
                }
            }).setCancelable(false).show();

        }

    }

    @Override
    public void onRefresh(FlyRefreshLayout view) {
        View child = mListView.getChildAt(0);
        if (child != null) {
            bounceAnimateView(child.findViewById(R.id.icon));
        }

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mFlylayout.onRefreshFinish();
            }
        }, 2000);
    }

    private void bounceAnimateView(View view) {
        if (view == null) {
            return;
        }

        Animator swing = ObjectAnimator.ofFloat(view, "rotationX", 0, 30, -20, 0);
        swing.setDuration(400);
        swing.setInterpolator(new AccelerateInterpolator());
        swing.start();
    }

    @Override
    public void onRefreshAnimationEnd(FlyRefreshLayout view) {
        addItemData();
    }

    private class ItemAdapter extends RecyclerView.Adapter<ItemViewHolder> {

        private LayoutInflater mInflater;
        private DateFormat dateFormat;

        public ItemAdapter(Context context) {
            mInflater = LayoutInflater.from(context);
            dateFormat = SimpleDateFormat.getDateInstance(DateFormat.DEFAULT, Locale.ENGLISH);
        }

        @Override
        public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            View view = mInflater.inflate(R.layout.view_list_item, viewGroup, false);
            return new ItemViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ItemViewHolder itemViewHolder, int i) {
            final ItemData data = mDataSet.get(i);
//            ShapeDrawable drawable = new ShapeDrawable(new OvalShape());
//            drawable.getPaint().setColor(data.color);
//            itemViewHolder.icon.setBackgroundDrawable(drawable);
            itemViewHolder.icon.setImageResource(data.icon);
            itemViewHolder.title.setText(data.title);
            itemViewHolder.subTitle.setText(dateFormat.format(data.time));
            itemViewHolder.onClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ShoppingListActivity.this, ShoppingActivity.class);
                    intent.putExtra("url", data.url);
                    ShoppingListActivity.this.startActivity(intent);
                }
            };
            itemViewHolder.icon.setOnClickListener(itemViewHolder.onClickListener);
        }

        @Override
        public int getItemCount() {
            return mDataSet.size();
        }
    }

    private static class ItemViewHolder extends RecyclerView.ViewHolder {

        ImageView icon;
        TextView title;
        TextView subTitle;
        View.OnClickListener onClickListener;

        public ItemViewHolder(View itemView) {
            super(itemView);
            icon = (ImageView) itemView.findViewById(R.id.icon);
            title = (TextView) itemView.findViewById(R.id.title);
            subTitle = (TextView) itemView.findViewById(R.id.subtitle);
        }

    }
}
